package com.daocheng.dc.book.auth.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.daocheng.dc.book.auth.constant.RedisKeyConstant;
import com.daocheng.dc.book.auth.enums.ResponseCodeEnum;
import com.daocheng.dc.book.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import com.daocheng.dc.book.auth.service.VerificationCodeService;
import com.daocheng.dc.book.auth.sms.AliyunSmsHelper;
import com.daocheng.framework.common.exception.BizException;
import com.daocheng.framework.common.response.Response;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName VerificationCodeServiceImpl
 * @author: 稻城
 * @date: 2025/3/17
 * @Version 1.0
 * @description: TODO
 */
@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    //要定义好线程池配置文件上的Bean的name
    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        //手机号
        String phone = sendVerificationCodeReqVO.getPhone();
        //构建验证码redis key
        String key = RedisKeyConstant.buildVerificationCodeKey(phone);
        //判断是否已发送验证码
        boolean isSent = redisTemplate.hasKey(key);
        if (isSent) {
            // 若之前发送的验证码未过期，则提示发送频繁
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        //生成6位随机数字组验证码
        String verificationCode = RandomUtil.randomNumbers(6);
        //Todo: 调用第三方短信发送服务
        log.info("发送验证码成功，手机号：{}，验证码：{}", phone, verificationCode);
        //调用第三方短信发送服务
//        threadPoolTaskExecutor.submit(() -> {
//            String signName = "阿里云短信测试";
//            String templateCode = "SMS_154950909";
//            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
//            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
//        });

        redisTemplate.opsForValue().set(key, verificationCode, 3, TimeUnit.MINUTES);

        return Response.success();
    }
}
